<template>
  <div>
    <!-- 第一步 - 创建任务 -->
    <div class="task-container">
      <el-form ref="taskForm" :model="taskData" :rules="rules">
      <!-- 任务基本信息 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>任务基本信息</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <!-- 配置项 - 任务名称 -->
            <div class="common-item item-5">
              <label class="condition-label">任务名称</label>
              <el-form-item class="condition-input" prop="name">
                <el-input type="text" :disabled="taskData.done" placeholder="请输入任务名称" v-model="taskData.name" />
              </el-form-item>
            </div>
            <!-- 配置项 - 平台 -->
            <div class="common-item item-5">
              <label class="condition-label">社交平台</label>
              <el-form-item class="condition-input" prop="system">
                <el-select :disabled="taskData.done" v-model="taskData.system" clearable placeholder="请选择平台">
                  <el-option v-for="(item, index) in systems" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 配置项 - 类型 -->
            <!-- <div class="common-item item-3">
              <label class="condition-label">任务类型</label>
              <el-form-item class="condition-input" prop="type">
                <el-select :disabled="taskData.done" v-model="taskData.type" clearable placeholder="请选择类型">
                  <el-option v-for="(item, index) in types" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div> -->
          </div>
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-10">
              <label class="condition-label">任务描述</label>
              <el-form-item class="condition-input" prop="description">
                <el-input :disabled="taskData.done" v-model="taskData.description" maxlength="100" type="textarea" show-word-limit :rows="4" resize="none" placeholder="请输入任务描述" />
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <!-- 公钥字段 -->
      <div class="data-show">
        <!-- 标题 -->
        <div class="data-actions data-title-between">
          <h3>密钥协商(发送)</h3> 
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-5">
              <label class="condition-label">发布用户</label>
              <el-form-item class="condition-input" prop="userID">
                <el-input :disabled="taskData.done" type="text" v-model="taskData.userID" placeholder="请输入用户" />
              </el-form-item>
            </div>
            <div class="common-item item-5">
              <label class="condition-label">目标用户</label>
              <el-form-item class="condition-input" prop="targetUserId">
                <el-input :disabled="taskData.done" type="text" v-model="taskData.targetUserId" placeholder="请输入用户" />
              </el-form-item>
            </div>
          </div>
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <!-- 配置项 - 算法类型 -->
            <div class="common-item item-5">
              <label class="condition-label">算法模块</label>
              <el-form-item class="condition-input" prop="keyType">
                <el-select :disabled="taskData.done" v-model="taskData.keyType" clearable placeholder="请选择算法模块">
                  <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 配置项 - 参数文件 -->
            <div class="common-item item-5">
              <label class="condition-label">参数文件</label>
              <el-form-item class="condition-input" prop="config">
                <el-select :disabled="taskData.done" v-model="taskData.config" clearable placeholder="请选择参数">
                  <el-option v-for="(item, index) in configs" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <transition name="upload">
        <!-- 按钮部分 -->
        <div class="btn-groups" v-if="!taskData.done">
          <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
          <button :disabled="taskData.createFlag" type="button" class="btn" @click="handleCreateTask">发送</button>
        </div>
        <!-- 公钥发布结果部分 -->
        <div class="data-show" v-else>
          <!-- 标题 -->
          <div class="data-actions data-title-between">
            <h3>密钥协商发送密文</h3>
            <div class="data-title-actions">
              <span class="action aniTxtBtn" @click="copyText('keyOneText', taskData, '密文为空，请稍后重试或联系管理员')">复制</span>
              <span class="action aniTxtBtn" @click="downText('keyOneText', taskData, '未提供密文，请稍后重试或联系管理员', 'keyOneText.json')">下载</span>
            </div>
          </div>
          <div class="data-table data-table-scroll">
            <p class="text-container">
              {{ changeJSON(taskData.keyOneText) }}
            </p>
          </div>
        </div>
      </transition>
      </el-form>
      <!-- 修改后的第二步 - 上传key2提取共享密钥进行身份认证 -->
      <el-form ref="shareKeyForm" :model="shareKey" :rules="rules" v-if="taskData.done">
        <div class="data-show">
          <!-- 头部标题 -->
          <div class="data-actions">
            <h3>协商密钥参数(接收)</h3>
          </div>
          <!-- 内容区 -->
          <div class="data-table">
            <!-- 通用布局行 - key2上传 -->
            <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.keyTwoTextFilePath.showFileList}">
                <el-tooltip content="切换上传方式" placement="top">
                  <label class="condition-label condition-label-change" @click="changeUploadType('keyTwoTextFilePath', shareKey)">协商密钥参数密文</label>
                </el-tooltip>
                <el-form-item class="condition-input" prop="keyTwoTextFilePath">
                  <el-upload
                    v-if="uploadObj.keyTwoTextFilePath.isUploadType"
                    class="upload"
                    :ref="uploadObj.uploadRef('keyTwoTextFilePath')"
                    drag
                    :disabled="shareKey.done"
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.keyTwoTextFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('keyTwoTextFilePath')"
                    :on-success="uploadObj.onSuccess('keyTwoTextFilePath', shareKey, shareKeyForm)"
                    :on-progress="uploadObj.onProgress('keyTwoTextFilePath')"
                    :on-error="uploadObj.onError('keyTwoTextFilePath')"
                    :on-remove="uploadObj.onRemove('keyTwoTextFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!shareKey.keyTwoTextFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.keyTwoTextFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                  <el-input v-else :disabled="shareKey.done" type="textarea" @input="clearData('keyTwoTextFilePath', shareKey)" @change="createBlobTxt($event, 'keyTwoTextFilePath', shareKey, shareKeyForm)" v-model="uploadObj.keyTwoTextFilePath.text"  show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <transition name="upload">
          <!-- 按钮部分 -->
          <div class="btn-groups" v-if="!shareKey.done">
            <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
            <button :disabled="shareKey.btnFlag" type="button" class="btn" @click="handleEmbeddingShareKey">解密参数</button>
          </div>
          <el-row :gutter="20" v-else>
            <el-col :span="12">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>参数展示</h3>
                </div>
                <div class="data-table data-table-scroll">
                  <p class="text-container">
                    {{ shareKey.keyTwo }}
                  </p>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>协商密钥</h3>
                </div>
                <div class="data-table data-table-scroll">
                  <p class="text-container">
                    {{ shareKey.keyThree }}
                  </p>
                </div>
              </div>
            </el-col>
          </el-row>
        </transition>
      </el-form>

      <!-- 第三部 - 载体签名嵌入 -->
      <el-form ref="promptForm" :model="promptData" :rules="rules" v-if="shareKey.done">
        <div class="data-show">
          <!-- 标题 -->
          <div class="data-actions data-title-between">
            <h3>签名生成、信息嵌入</h3> 
          </div>
          <!-- 内容区 -->
          <div class="data-table">
            <!-- 通用布局行 -->
            <div class="common-row row-between">
              <div class="common-item item-5">
                <label class="condition-label">参数文件</label>
                <el-form-item class="condition-input" prop="parameter">
                  <el-select :disabled="promptData.done" v-model="promptData.parameter" clearable placeholder="请选择参数文件">
                    <el-option v-for="(item, index) in parameters" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="common-item item-5">
                <label class="condition-label">媒体类型</label>
                <el-form-item class="condition-input" prop="module">
                  <el-select @change="moduleChange" :disabled="promptData.done" v-model="promptData.module" clearable placeholder="请选择类型">
                    <el-option v-for="(item, index) in modules" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <!-- 通用布局行 - 任务prompt -->
            <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.promptFilePath.showFileList}">
                <el-tooltip content="切换上传方式" placement="top">
                  <label class="condition-label condition-label-change" @click="changeUploadType('promptFilePath', promptData)">提示词</label>
                </el-tooltip>
                <el-form-item class="condition-input" prop="promptFilePath">
                  <!-- todo - 这里要添加accept做文件选择限制 -->
                  <el-upload
                    v-if="uploadObj.promptFilePath.isUploadType"
                    class="upload"
                    :ref="uploadObj.uploadRef('promptFilePath')"
                    drag
                    :disabled="promptData.done"
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.promptFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('promptFilePath')"
                    :on-success="uploadObj.onSuccess('promptFilePath', promptData, promptForm)"
                    :on-progress="uploadObj.onProgress('promptFilePath')"
                    :on-error="uploadObj.onError('promptFilePath')"
                    :on-remove="uploadObj.onRemove('promptFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!promptData.promptFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.promptFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                  <el-input v-else :disabled="promptData.done" type="textarea" @input="clearData('promptFilePath', promptData)" @change="createBlobTxt($event, 'promptFilePath', promptData, promptForm)" v-model="uploadObj.promptFilePath.text" maxlength="255" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
                </el-form-item>
              </div>
            </div>
            <!-- 通用布局行 - 任务密钥 -->
            <!-- <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.keyFilePath.showFileList}">
                <label class="condition-label">协商密钥</label>
                <el-form-item class="condition-input" prop="keyFilePath">
                  <el-upload
                    class="upload"
                    :ref="uploadObj.uploadRef('keyFilePath')"
                    drag
                    :disabled="promptData.done"
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.keyFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('keyFilePath')"
                    :on-success="uploadObj.onSuccess('keyFilePath', promptData)"
                    :on-progress="uploadObj.onProgress('keyFilePath')"
                    :on-error="uploadObj.onError('keyFilePath')"
                    :on-remove="uploadObj.onRemove('keyFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!promptData.keyFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.keyFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                </el-form-item>
              </div>
            </div> -->
            <!-- 通用布局行 - message -->
            <div class="common-row">
              <div class="common-item item-10" :class="{'item-upload': uploadObj.messageFilePath.showFileList}">
                <label class="condition-label">消息文件</label>
                <el-form-item class="condition-input" prop="messageFilePath">
                  <el-upload
                    class="upload"
                    :ref="uploadObj.uploadRef('messageFilePath')"
                    drag
                    :disabled="promptData.done"
                    :action="uploadObj.uploadUrl"
                    :limit="1"
                    :show-file-list="uploadObj.messageFilePath.showFileList"
                    :before-upload="uploadObj.beforeUpload('messageFilePath')"
                    :on-success="uploadObj.onSuccess('messageFilePath', promptData, promptForm)"
                    :on-progress="uploadObj.onProgress('messageFilePath')"
                    :on-error="uploadObj.onError('messageFilePath')"
                    :on-remove="uploadObj.onRemove('messageFilePath')"
                  >
                    <transition name="upload">
                      <div class="upload-empty" v-if="!promptData.messageFilePath">
                        <i class="iconfont icon-icon_update upload-icon"></i>
                        <p class="upload-des">拖拽文件至此或点击上传</p>
                      </div>
                      <div class="upload-content" v-else>
                        <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                        <p class="upload-des">{{ uploadObj.messageFilePath.fileName }}</p>
                      </div>
                    </transition>
                  </el-upload>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <transition name="upload">
            <!-- 按钮部分 -->
            <div class="btn-groups" v-if="!promptData.done">
              <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
              <button type="button" :disabled="promptData.btnFlag" class="btn" @click="handleEmbeddingSign">签名和嵌入</button>
            </div>
            <div v-else>
              <!-- 签名展示 -->
              <el-row :gutter="20">
                <!-- stego载体文件 -->
                <el-col :span="12">
                  <div class="data-show">
                    <!-- 标题 -->
                    <div class="data-actions data-title-between">
                      <h3>载密文件</h3>
                      <div class="data-title-actions">
                        <span class="action aniTxtBtn" @click="downloadFile">下载</span>
                      </div>
                    </div>
                    <div class="data-table data-table-scroll">
                      <el-image class="file-image" v-if="promptData.module === '图像'" :src="promptData.stego" fit="contain" :preview-src-list="[promptData.stego]" />
                      <p v-else-if="promptData.module === '文本'" class="text-container">
                        {{ promptData.stego }}
                      </p>
                      <div class="audio-container audio-show" v-else>
                        <i class="iconfont icon-swticonyinle audio-icon"></i>
                        <p class="audio-filename">{{ promptData.stego }}</p>
                        <!-- <audio ref="audio" class="audio" :src="promptData.stego" controls></audio> -->
                      </div>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="data-show">
                    <!-- 标题 -->
                    <div class="data-actions data-title-between">
                      <h3>签名结果</h3>
                      <div class="data-title-actions">
                        <span class="action aniTxtBtn" @click="copyText('signature', promptData, '签名文件为空，请稍后重试或联系管理员')">复制</span>
                        <span class="action aniTxtBtn" @click="downText('signature', promptData, '暂未提供签名文件，请稍后重试或联系管理员', 'signature.json')">下载</span>
                      </div>
                    </div>
                    <div class="data-table data-table-scroll">
                      <p class="text-container">
                        {{ changeJSON(promptData.signature) }}
                      </p>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </transition>
      </el-form>
    </div>
  </div>
  
</template>
<script setup>
import useAppStore from '@/stores/app';
import { ref, computed, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { API } from '@/utils/status.js';
import { ElMessage } from 'element-plus';
import * as uploadApi from '@/api/file';
import * as rule from '@/utils/rules.js';
import * as request from '@/api/steganography';

// 假数据
const systems = API.steganography.systems;
const types = [
  { value: 0, label: '类型1' },
  { value: 1, label: '类型2' }
];
const router = useRouter();
const route = useRoute();
const configs = [
  { value: 'config1', label: 'ECC参数文件' },
  { value: 'config2', label: 'RSA参数文件' }
];
const keyTypes = API.publicSteg.keyTypes;
const parameters = API.steCommon.parameters;
const modules = API.steCommon.modules;
const defaultTaskData = {
  done: false,
  createFlag: false,
  id: null,
  name: '',
  description: '',
  system: null,
  type: null,
  userID: null,
  targetUserId: null,
  keyType: null,
  config: null,
  // 公钥密文
  keyOneText: null
};
const defaultShareKey = {
  done: false,
  btnFlag: false,
  // 共享密文
  keyTwoTextFilePath: null,
  // 共享密钥
  keyTwo: null,
  keyThree: null
};
const defaultPromptData = {
  done: false,
  btnFlag: false,
  module: null,
  parameter: null,
  promptFilePath: null,
  keyFilePath: null,
  messageFilePath: null,
  signature: null,
  embeddingFilePath: null,
  stego: null
};
const defaultUpload = {
  isUploadType: true,
  text: '',
  dom: null,
  showFileList: false,
  fileName: '',
  uploading: false
}
// ============> data <============
const appStore = useAppStore();
const taskForm = ref(null);
const shareKeyForm = ref(null);
const promptForm = ref(null);
// 创建任务步骤的表单对象
const taskData = ref({
  done: false,
  createFlag: false,
  id: null,
  name: '',
  description: '',
  system: null,
  type: null,
  userID: null,
  targetUserId: null,
  keyType: null,
  config: null,
  // 公钥密文
  keyOneText: null
});
// 第二步共享密钥对象
const shareKey = ref({
  done: false,
  btnFlag: false,
  // 共享密文
  keyTwoTextFilePath: null,
  // 共享密钥
  keyTwo: null,
  keyThree: null
})
// 第二步的表单对象
const promptData = ref({
  done: false,
  btnFlag: false,
  module: '图像',
  parameter: null,
  promptFilePath: null,
  keyFilePath: null,
  messageFilePath: null,
  signature: null,
  embeddingFilePath: null,
  stego: null
});
// 第二步的上传控制对象
const uploadObj = ref({
  uploadUrl: `${import.meta.env.VITE_FILE_BASE_API}${uploadApi.uploadUrl}`,
  uploadRef(key){
    return function (dom){
      if (dom){
        uploadObj.value[key].dom = dom;
      }
    }
  },
  beforeUpload(key){
    return function (file){
      if (uploadObj.value[key].uploading){
        ElMessage.warning('当前有文件正在上传，请稍后重试');
        return false;
      }
      let extension = file.size < API.upload.commonLimit;
      if (!extension) {
        ElMessage.warning(`上传文件超过大小限制，文件须小于${API.upload.commonLimit / (1024 * 1024)}M`)
      }
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (key === 'keyTwoTextFilePath'){
        extension = fileType == 'json' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为json文件!');
        }
      }
      if (key === 'promptFilePath' || (key === 'messageFilePath' && promptData.value.module == '文本')){
        extension = fileType == 'txt' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为.txt文件!');
        }
      }
      if (key === 'keyFilePath'){
        extension = fileType == 'yaml' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为yaml文件!');
        }
      }
      uploadObj.value[key].fileName = extension ? file.name : '';
      uploadObj.value[key].showFileList = true;
      return extension;
    }
  },
  onSuccess(key, data, form){
    return function (e){
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      console.log('上传res')
      console.log(e)
      if (e.code === API.code.SUCCESS) { 
        ElMessage.success('上传成功');
        data[key] = e.data.path;
      } else {
        let msg = e.msg || e.message || '上传失败，请稍后重试或联系管理员';
        ElMessage({
          type: 'error',
          duration: 1500,
          message: msg
        });
      }
      form.validateField([key])
    }
  },
  onProgress(key){
    return function (e){
      uploadObj.value[key].showFileList = true;
      uploadObj.value[key].uploading = true;
    }
  },
  onError(key){
    return function (e){
      console.log(e)
      let message = e.msg || e.message || '上传失败，请稍后重试或联系管理员'
      ElMessage({
        type: 'error',
        duration: 1500,
        message
      });
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  onRemove(key){
    return function (e){
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  keyTwoTextFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  promptFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  keyFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  messageFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  }
});
// 表单验证规则
const rules = {
  name: rule.createRequired('任务名称不能为空'),
  userID: rule.createRequired('请输入用户'),
  targetUserId: rule.createRequired('请输入目标用户'),
  keyType: rule.createRequired('请选择算法模块'),
  // keyTwoTextFilePath: rule.createRequired('请上传协商密钥参数密文'),
  keyTwoTextFilePath: rule.createTextUpload(uploadObj.value, 'keyTwoTextFilePath', '协商密钥参数密文不能为空'),
  module: rule.createRequired('请选择媒体类型'),
  // promptFilePath: rule.createRequired('请上传提示词'),
  promptFilePath: rule.createTextUpload(uploadObj.value, 'promptFilePath', '提示词不能为空'),
  // keyFilePath: rule.createRequired('请上传协商密钥'),
  messageFilePath: rule.createRequired('请上传消息文件')
};
const changeJSON = computed(() => {
  return function (jsonString){
    return jsonString ? window.decodeURIComponent(JSON.parse(jsonString)) : '';
  }
})

// ============> hooks <============
onActivated(() => {
  let { id, isCreate, reenter } = route.query;
  if (reenter || (id !== undefined && id == taskData.value.id)){
    return;
  }
  if (isCreate){
    init();
    return;
  }
  reInit();
});

// ============> methods <============
function init(){
  taskData.value = Object.assign({}, defaultTaskData);
  shareKey.value = Object.assign({}, defaultShareKey);
  promptData.value = Object.assign({}, defaultPromptData);
  uploadObj.value.promptFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.keyFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.messageFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.keyTwoTextFilePath = Object.assign({}, defaultUpload);
}
function reInit(){
  let { id } = route.query;
  init();
  request.getTaskDetailById({id})
    .then(res => {
      let result = res;
      result.infoData = JSON.parse(res.infoData);
      console.log(result);
      taskData.value.id = result.id;
      taskData.value.name = result.name;
      taskData.value.description = result.description;
      taskData.value.userID = result.infoData.userID;
      taskData.value.targetUserId = result.infoData.targetUserId;
      taskData.value.keyType = result.infoData.keyType;
      taskData.value.config = result.infoData.config;
      taskData.value.createFlag = false;
      if (result.infoData.keyOneText){
        taskData.value.keyOneText = result.infoData.keyOneText;
        taskData.value.done = true;
      }
      if (result.infoData.keyTwo && result.infoData.keyThree){
        shareKey.value.done = true;
        shareKey.value.btnFlag = false;
        shareKey.value.keyTwoTextFilePath = result.infoData.keyTwoTextFilePath;
        uploadObj.value.keyTwoTextFilePath.fileName = 'keyTwoText.json';
        shareKey.value.keyTwo = result.infoData.keyTwo;
        shareKey.value.keyThree = result.infoData.keyThree;
      }
      console.log(!!result.infoData.signature)
      if (result.infoData.signature){
        promptData.value.done = true;
        promptData.value.btnFlag = false;
        promptData.value.signature = result.infoData.signature;
        promptData.value.module = result.infoData.module;
        promptData.value.parameter = result.infoData.parameter;
        promptData.value.promptFilePath = result.infoData.promptFilePath;
        promptData.value.keyFilePath = result.infoData.keyFilePath;
        promptData.value.messageFilePath = result.infoData.messageFilePath;
        promptData.value.signature = result.infoData.signature;
        promptData.value.embeddingFilePath = result.infoData.embeddingFilePath;
        uploadObj.value.promptFilePath.fileName = 'prompt.txt';
        uploadObj.value.keyFilePath.fileName = 'key.yaml';
        uploadObj.value.messageFilePath.fileName = 'message.txt';
        uploadApi.download({filePath: promptData.value.embeddingFilePath})
          .then(res => {
            if (promptData.value.module === '图像') {
              promptData.value.stego = window.URL.createObjectURL(res.data);
            } else if (promptData.value.module === '文本') {
              let reader = new FileReader();
              reader.readAsText(res.data, 'UTF-8');
              reader.onload= function(evt){
                promptData.value.stego = evt.target.result || ''
                console.log(promptData.value.stego)
              }
            } else {
              console.log('调试')
              // let disposition = res.headers['content-disposition'],
              //     filename = disposition.slice(disposition.lastIndexOf('=') + 1);
              // console.log(disposition)
              // console.log(filename)
              // promptData.value.stego = filename;
              let origin = promptData.value.embeddingFilePath,
                  index;
              if (origin.lastIndexOf('\\') > 0){
                index = origin.lastIndexOf('\\');
              } else if (origin.lastIndexOf('/') > 0){
                index = origin.lastIndexOf('/');
              }
              let filename = origin.slice(index + 1);
              promptData.value.stego = filename ? filename : 'stego';
            }
          })
      }
    })
}
function initUploadKeyObj(key){
  uploadObj.value[key].isUploadType = true;
  uploadObj.value[key].text = '';
  uploadObj.value[key].showFileList = false;
  uploadObj.value[key].fileName = '';
  uploadObj.value[key].uploading = false;
  if (uploadObj.value[key].dom) uploadObj.value[key].dom.clearFiles();
}
function changeUploadType(key, data){
  if (data.done){
    return;
  }
  uploadObj.value[key].isUploadType = !uploadObj.value[key].isUploadType;
  uploadObj.value[key].text = '';
  uploadObj.value[key].showFileList = false;
  uploadObj.value[key].fileName = '';
  uploadObj.value[key].uploading = false;
  data[key] = null;
}
function clearData(key, data){
  data[key] = '';
}
// 上传项文本输入事件
function createBlobTxt(e, key, data, form){
  if (!e){
    data[key] = '';
    ElMessage.success('上传成功');
    return;
  }
  let fileType, filename;
  switch (key){
    case 'keyTwoTextFilePath':
      filename = 'keyTwoText.json';
      fileType = 'application/json';
      break;
    case 'promptFilePath':
      filename = 'prompt.txt';
      fileType = 'text/plain';
      break;
  }
  const blob = new Blob([e], { type: fileType });
  const txt = new File([blob], filename, { type: fileType });
  let formData = new FormData();
  formData.append('file', txt);
  uploadApi.upload(formData)
    .then(res => {
      ElMessage.success('上传成功');
      data[key] = res.path;
      form.validateField([key])
    })
    .catch(err => {
      console.log(err)
      let msg = err.msg || err.message || '上传失败，请稍后重试或联系管理员';
      ElMessage.error(msg);
      form.validateField([key])
    })
}
// 通用复制
function copyText(key, data, warning = '内容为空，请稍后重试或联系管理员'){
  if (!data[key]) {
    ElMessage.warning(warning);
    return;
  }
  if (navigation.clipboard){
    navigation.clipboard.writeText(data[key])
      .then(res => {
        ElMessage.success('已复制到剪切板');
      })
      .catch(err => {
        ElMessage.error('复制失败');
      })
  } else if (document.execCommand){
    const textarea = document.createElement('textarea');
    textarea.value = data[key];
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful){
        ElMessage.success('已复制到剪切板');
      } else {
        ElMessage.error('复制失败');
      }
    } catch(err){
      console.log('sss')
      ElMessage.error(err);
    }
    document.body.removeChild(textarea); 
  }
}
// 通用下载
function downText(key, data, warning = '下载内容为空，请稍后再试或联系管理员', filename){
  if (!data[key]){
    ElMessage.warning(warning);
    return;
  }
  const blob = new Blob([data[key]], { type: 'application/json' });
  const link = document.createElement('a');
  const fileUrl = window.URL.createObjectURL(blob);
  link.href = fileUrl;
  link.download = filename;
  ElMessage.success('下载开始');
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
// 载体下载
function downloadFile(){
  uploadApi.download({filePath: promptData.value.embeddingFilePath})
    .then(res => {
      console.log(res)
      let fileUrl = window.URL.createObjectURL(res.data),
          a = document.createElement('a');
          // disposition = res.headers['content-disposition'],
          // filename = disposition.slice(disposition.lastIndexOf('=') + 1);
      let origin = promptData.value.embeddingFilePath,
          index;
      if (origin.lastIndexOf('\\') > 0){
        index = origin.lastIndexOf('\\');
      } else if (origin.lastIndexOf('/') > 0){
        index = origin.lastIndexOf('/');
      }
      let filename = origin.slice(index + 1);
      a.href = fileUrl;
      a.download = filename;
      a.click();
      ElMessage.success('下载开始！');
      window.URL.revokeObjectURL(fileUrl);
    })
    .catch(err => {
      let message = err.msg || err.message || err.data.msg || '下载失败，请稍后重试或联系管理员';
      ElMessage.error(message);
    })
}
function moduleChange(){
  promptData.value.messageFilePath = null;
  initUploadKeyObj('messageFilePath')
}
// 点击取消事件
function handleCancel(){
  router.back();
}
// 第一步 - 发布公钥创建任务
function handleCreateTask(){
  if (taskData.value.createFlag){
    ElMessage.warning('当前正在发送协商密钥参数，请稍后');
    return;
  }
  taskForm.value.validate(valid => {
    if (valid){
      taskData.value.createFlag = true;
      appStore.openLoading('发送参数中...');
      request.applicationOneEmbeddingPublicKey({
        name: taskData.value.name,
        moduleType: API.steganography.moduleType.APPONE,
        taskType: API.steganography.type.IMPLANT,
        description: taskData.value.description,
        infoData: {
          userID: taskData.value.userID,
          targetUserId: taskData.value.targetUserId,
          keyType: taskData.value.keyType,
          config: taskData.value.config
        }
      })
        .then(res => {
          taskData.value.createFlag = false;
          appStore.closeLoading();
          if (res && res.infoData && res.infoData.keyOneText){
            ElMessage.success('参数发送成功!');
            taskData.value.id = res.id;
            taskData.value.keyOneText = res.infoData.keyOneText;
            taskData.value.done = true;
          } else {
            ElMessage.error('参数发送失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          appStore.closeLoading();
          taskData.value.createFlag = false;
        })
    } else {
      ElMessage.warning('填写信息有误，请核对后提交');
    }
  })
}
// 第二步 - 嵌入共享密钥
function handleEmbeddingShareKey(){
  if (!taskData.value.id && taskData.value.id !== 0 && taskData.value.id !== '0'){
    ElMessage.error('任务不存在，请稍后重试或联系管理员');
    return;
  }
  if (shareKey.value.btnFlag){
    ElMessage.warning('当前正在解密参数，请稍后');
    return;
  }
  shareKeyForm.value.validate(valid => {
    if (valid){
      shareKey.value.btnFlag = true;
      appStore.openLoading('参数解密中...');
      request.applicationOneEmbeddingSharedKey({
        id: taskData.value.id,
        name: taskData.value.name,
        moduleType: API.steganography.moduleType.APPONE,
        taskType: API.steganography.type.IMPLANT,
        description: taskData.value.description,
        infoData: {
          userID: taskData.value.userID,
          targetUserId: taskData.value.targetUserId,
          keyType: taskData.value.keyType,
          config: taskData.value.config,
          keyTwoTextFilePath: shareKey.value.keyTwoTextFilePath,
          keyOne: taskData.value.keyOneText
        }
      })
        .then(res => {
          console.log(res);
          shareKey.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.infoData && res.infoData.keyTwo && res.infoData.keyThree){
            ElMessage.success('解密参数成功!');
            shareKey.value.keyTwo = res.infoData.keyTwo;
            shareKey.value.keyThree = res.infoData.keyThree;
            shareKey.value.done = true;
          } else {
            ElMessage.error('解密参数失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          appStore.closeLoading();
          shareKey.value.btnFlag = false;
        })
    } else {
      ElMessage.warning('填写信息有误，请核对后提交');
    }
  })
}
// 第三步 - 发布签名
function handleEmbeddingSign(){
  if (promptData.value.btnFlag){
    ElMessage.warning('当前正在执行签名生成、信息嵌入，请稍后');
    return;
  }
  promptForm.value.validate(valid => {
    if (valid){
      promptData.value.btnFlag = true;
      appStore.openLoading('签名生成、信息嵌入中...');
      request.applicationOneEmbeddingSign({
        id: taskData.value.id,
        name: taskData.value.name,
        moduleType: API.steganography.moduleType.APPONE,
        taskType: API.steganography.type.IMPLANT,
        description: taskData.value.description,
        infoData: {
          userID: taskData.value.userID,
          targetUserId: taskData.value.targetUserId,
          keyType: taskData.value.keyType,
          config: taskData.value.config,
          module: promptData.value.module,
          parameter: promptData.value.parameter,
          promptFilePath: promptData.value.promptFilePath,
          // keyFilePath: promptData.value.keyFilePath,
          messageFilePath: promptData.value.messageFilePath
        }
      })
        .then(res => {
          promptData.value.btnFlag = false;
          appStore.closeLoading();
          if (res && res.infoData && res.infoData.signature){
            ElMessage.success('签名生成、信息嵌入成功!');
            promptData.value.signature = res.infoData.signature;
            promptData.value.done = true;
            if (res.infoData.embeddingFilePath){
              // todo - 这里要做结果未提供embeddingFilePath的情况，页面上要做未提供结果的回显
              promptData.value.embeddingFilePath = res.infoData.embeddingFilePath;
              uploadApi.download({filePath: res.infoData.embeddingFilePath})
                .then(res => {
                  console.log(res)
                  if (promptData.value.module === '图像') {
                    promptData.value.stego = window.URL.createObjectURL(res.data);
                  } else if (promptData.value.module === '文本') {
                    let reader = new FileReader();
                    console.log(reader)
                    reader.readAsText(res.data, 'UTF-8');
                    reader.onload= function(evt){
                      promptData.value.stego = evt.target.result || ''
                      console.log(promptData.value.stego)
                    }
                  } else {
                    // let disposition = res.headers['content-disposition'],
                    //     filename = disposition.slice(disposition.lastIndexOf('=') + 1);
                    let origin = promptData.value.embeddingFilePath,
                        index;
                    if (origin.lastIndexOf('\\') > 0){
                      index = origin.lastIndexOf('\\');
                    } else if (origin.lastIndexOf('/') > 0){
                      index = origin.lastIndexOf('/');
                    }
                    let filename = origin.slice(index + 1);
                    promptData.value.stego = filename;
                  }
                  console.log(promptData.value.stego);
                })
            }
          } else {
            ElMessage.error('签名生成、信息嵌入失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          appStore.closeLoading();
          promptData.value.btnFlag = false;
        })
    } else {
      ElMessage.warning('填写信息有误，请核对后提交');
    }
  })
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-5 {
  width: 49%;
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 20px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.item-10-spe {
  width: 100%;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
  &::v-deep .el-form-item__content {
    align-items: center!important;
  }
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    display: flex;
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.item-upload {
  padding-bottom: 50px;
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
}
.condition-label-change {
  cursor: pointer;
}
.condition-label-change:hover {
  color: var(--color-primary);
}
.data-table-scroll {
  max-height: 220px;
  height: auto;
  overflow-y: auto;
  @include scrollBar;
  .file-image {
    width: 100%;
    height: 190px;
    background-color: var(--color-gray-2);
    border: 1px solid var(--color-main-border);
    border-radius: 6px;
  }
}
.item-upload {
  padding-bottom: 50px;
}
.audio-container {
  width: 100%;
  height: 190px;
  background-color: var(--color-gray-2);
  border: 1px solid var(--color-main-border);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  @include flex-all-center;
  .audio-icon {
    font-size: 40px;
    font-weight: bolder;
    color: var(--color-main);
  }
  .audio {
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 105%;
    height: 30px;
    transform: translateX(-50%);
  }
}
.audio-show {
  @include flex-all-center;
  flex-direction: column;
}
.audio-show > .audio-filename {
  margin-top: 10px;
  color: var(--color-main);
}
</style>